#include "MyFileSystem.h"
#include<dirent.h>//文件系统库
#include<iostream>
#include<sys/stat.h>//文件信息
MyFileSystem::MyFileSystem(const std::string &path)
{
  TreeNode *rootpath=new TreeNode(path);
  rootpath->Connect(tree.GetRoot());//将传进来节点连在根节点上
  ExploreDir(rootpath,path);//进行递归
  
}
std::string DoubleToStr(double n,int fixed=2)//保留的位数
{
    std::string s=std::to_string(n);
    return s.substr(0,s.find('.')+fixed+1);//find找到.的前面的位置，保留两位小数要加一跳过.
}

void MyFileSystem::FindByFileName(const std::string &name)
{          

       doubleLinkList list=tree.FindByelement(name);
       for(size_t i=0;i<list.Size();i++)
       {
        std::string path;
        TreeNode *node=(TreeNode*)*list.findByIndex(i);
        path=node->GetData();
        while(node->Getparent()!=nullptr&&node->Getparent()!=tree.GetRoot())
        {
            path=node->Getparent()->GetData()+"/"+path;
            node=node->Getparent();
        }
        std::cout<<path<<std::endl;
       }
}
std::string Transform(long size)
{
  if(size<1024)
        return std::to_string(size)+"B";
  else if(size<1024*1024)
        return  DoubleToStr( 1.0* size/1024) +"KB";
  else if(size<1024*1024*1024)
        return  DoubleToStr( 1.0* size/1024/1024) +"MB";
  else 
        return  DoubleToStr( 1.0* size/1024/1024/1024) +"GB";
    
}

void MyFileSystem::ExploreDir(TreeNode *parent, const std::string &path)
{
  DIR *dir=opendir(path.c_str());//转化成c的const char *
  if(dir==nullptr)
  {
    std::cout<<"文件夹路径有误！\n";
    return;
  }
  dirent*d=readdir(dir);//读取文件夹下的文件
  while((d=readdir(dir))!=nullptr)
  {
    std::string dname(d->d_name);
    if(dname!="."&&dname!="..")
    {
     TreeNode *node=new TreeNode(dname);
     node->Connect(parent);   
     if(d->d_type==DT_DIR)//如果是文件夹就要往下递归
      {
        ExploreDir(node,path+"/"+dname);//node是parent的子节点
      }
    else
    {
       struct stat s;
       stat((path+"/"+dname).c_str(),&s);//根据路径获取文件信息
       char name[512]={0};
       sprintf(name,"%-30s size:%s",dname.c_str(),Transform(s.st_size).c_str());
       node->setData(name);
    }
    }
  }
     closedir(dir);//关闭文件接口
}
